import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 卖票案例
 * @ClassName: SaleTicketDemo
 * @Author: liugui
 * @Date: 2021-07-26 11:06
 **/
public class SaleTicketDemo {
    public static void main(String[] args) {
        // 多线程操作同一个资源类
        //Ticket ticket = new Ticket();
        Ticket2 ticket = new Ticket2();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"C").start();

    }
}

/**
 * 传统 synchronized
 */
class Ticket{
    private int number = 20;
    // 锁
    public synchronized void sale(){
        if (number > 0){
            number--;
            System.out.println(Thread.currentThread().getName() + ">卖出了1票，剩余：" + number);
        }else {
            System.out.println(Thread.currentThread().getName()+">票卖完了，不要来了");
        }
    }
}

/**
 * lock 锁
 * 常用：可重入锁 ReadLock ，WriteLock
 * NonfairSync 非公平锁
 * FairSync 公平锁
 */
class Ticket2{
    private int number = 30;
    Lock lock = new ReentrantLock();
    public void sale(){
        lock.lock();
        try {
            if (number > 0){
                number--;
                System.out.println(Thread.currentThread().getName() + ">卖出了1票，剩余：" + number);
            }else {
                System.out.println(Thread.currentThread().getName()+">票卖完了，不要来了");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}